'use client';

import type { TMetadata } from '@/types';
import { useQuery } from '@tanstack/react-query';
import { clientQueryAllSection } from '@/services/api';
import type { ISectionClient } from '@/interfaces';
import ErrorPage from '@/app/[locale]/error/error';
import LoadPage from '@/app/[locale]/load/load';
import Image from 'next/image';
import classNames from 'classnames';
import classs from './section.module.scss';
import Link from 'next/link';
import { isHttpOrHttps } from '@/lib/tool';
import { NavbarPage } from '@/app/[locale]/navbar';
import FooterPage from '@/app/[locale]/footer';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import { useTranslations } from 'use-intl';

export default function SectionPage({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <NavbarPage metadata={metadata} />
      <Section metadata={metadata} />
      <FooterPage metadata={metadata} />
    </>
  );
}

const Section = ({ metadata }: { metadata: TMetadata }) => {
  const t = useTranslations('SectionPage');

  const clientQueryAllSectionQuery = useQuery(
    metadata.all['sections'].k,
    async () => {
      return (await clientQueryAllSection()) as ISectionClient[];
    },
    {
      initialData: metadata.all['sections'].v as ISectionClient[],
    },
  );

  if (clientQueryAllSectionQuery.data) {
    const sections = clientQueryAllSectionQuery.data;
    const defaultSgKey = '0_0';
    const data = sections.reduce(
      (previousValue, currentValue) => {
        if (currentValue.sectionGroup) {
          const id =
            currentValue.sectionGroup.id + '_' + currentValue.sectionGroup.sort;
          if (id in previousValue) {
            previousValue[id].push(currentValue);
          } else {
            previousValue[id] = [currentValue];
          }
        } else {
          previousValue[defaultSgKey].push(currentValue);
        }
        return previousValue;
      },
      { [defaultSgKey]: [] } as {
        [id: string]: ISectionClient[];
      },
    );

    return (
      <div className="col px-0">
        <div className="card border-0">
          <div className="card-body">
            {sections.length > 0 ? (
              <div className="container-fluid py-4">
                <div className="row gap-5">
                  {Object.keys(data).length === 1 ? (
                    <div className="col-12">
                      <div className={classNames(classs.box)}>
                        {data[defaultSgKey].map((item) => {
                          return (
                            <SectionItem
                              key={item.id}
                              item={item}
                              metadata={metadata}
                            />
                          );
                        })}
                      </div>
                    </div>
                  ) : (
                    <>
                      {Object.keys(data)
                        .sort((a, b) =>
                          a === defaultSgKey || b === defaultSgKey
                            ? -1
                            : parseInt(b.split('_')[1]) -
                              parseInt(a.split('_')[1]),
                        )
                        .filter((key) => data[key].length > 0)
                        .map((key) => {
                          return (
                            <div key={key} className="col-12">
                              <div className="mb-4 d-flex justify-content-between">
                                <div className="h4">
                                  {key === defaultSgKey
                                    ? t('otherContent')
                                    : data[key][0].sectionGroup?.name}
                                </div>
                                <div>
                                  <i className="bi bi-arrow-right fs-4"></i>
                                </div>
                              </div>
                              <div className={classNames(classs.box)}>
                                {data[key].map((item) => {
                                  return (
                                    <SectionItem
                                      key={item.id}
                                      item={item}
                                      metadata={metadata}
                                    />
                                  );
                                })}
                              </div>
                            </div>
                          );
                        })}
                    </>
                  )}
                </div>
              </div>
            ) : (
              <Nodata isVh100 />
            )}
          </div>
        </div>
      </div>
    );
  }

  if (clientQueryAllSectionQuery.error) {
    return <ErrorPage error={clientQueryAllSectionQuery.error} />;
  }

  return <LoadPage />;
};

const SectionItem = ({
  item,
  metadata,
}: {
  item: ISectionClient;
  metadata: TMetadata;
}) => {
  const t = useTranslations('SectionPage');
  const env = metadata.env;

  return (
    <div className={classNames('card border-0 rounded', classs.item)}>
      <div className="card-body">
        {item.cover && (
          <div className="position-relative overflow-hidden">
            <Image
              className="rounded w-100 h-auto object-fit-cover"
              src={
                isHttpOrHttps(item.cover)
                  ? item.cover
                  : env.APP_OSS_SERVER + item.cover
              }
              width={0}
              height={0}
              alt={item.name}
              title={item.name}
              placeholder="blur"
              blurDataURL={env.APP_BLUR_DATA_URL}
              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
            />
          </div>
        )}

        <div className="container">
          {item.admins.length > 0 && (
            <div
              className="my-4 position-relative w-100"
              style={{ height: 48 }}
            >
              {item.admins.slice(0, 5).map((item, index) => {
                return (
                  <div
                    key={item.id}
                    className="position-absolute"
                    style={{
                      left: index * 33,
                      zIndex: index + 1,
                    }}
                  >
                    <Link
                      title={`${item.alias}(${item.id})`}
                      className="text-decoration-none text-decoration-underline-hover link-secondary"
                      href={`/users/${item.id}`}
                    >
                      {item.details && item.details.smallAvatarUrl ? (
                        <Image
                          className="rounded-circle"
                          src={
                            isHttpOrHttps(item.details.smallAvatarUrl)
                              ? item.details.smallAvatarUrl
                              : env.APP_OSS_SERVER + item.details.smallAvatarUrl
                          }
                          alt={item.alias || ''}
                          title={item.alias || ''}
                          placeholder="blur"
                          blurDataURL={env.APP_BLUR_DATA_URL}
                          width={48}
                          height={48}
                        />
                      ) : (
                        <Image
                          className="rounded-circle"
                          src="/images/avatar.png"
                          alt="avatar"
                          placeholder="blur"
                          blurDataURL={env.APP_BLUR_DATA_URL}
                          width={48}
                          height={48}
                        />
                      )}
                    </Link>
                  </div>
                );
              })}
              {item.admins.length > 5 && (
                <div
                  className="position-absolute fs-5 link-secondary"
                  style={{ left: 198, top: 6 }}
                >
                  <Link
                    className="text-decoration-none text-decoration-underline-hover link-secondary"
                    href={`/sections/${item.id}`}
                  >
                    +{item.admins.length - 5}
                  </Link>
                </div>
              )}
            </div>
          )}

          <p className="h5 my-4">
            <Link
              href={`/sections/${item.id}`}
              className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
            >
              {item.name}
            </Link>
          </p>

          {item.overview && (
            <p
              className="text-wrap text-truncate yw-line-clamp-3 text-secondary"
              dangerouslySetInnerHTML={{
                __html: item.overview,
              }}
            ></p>
          )}

          <p>
            <Link
              href={`/sections/${item.id}`}
              className="text-decoration-none position-relative"
            >
              {t('enterContent')}
              <i
                className="bi bi-arrow-up-short align-middle d-inline-block fs-4"
                style={{ transform: 'rotate(45deg)' }}
              ></i>
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
};
